package com.cneiu.ppms.web.base;

import java.util.HashMap;
import java.util.Map;

import com.cneiu.ppms.component.Success;
import com.cneiu.ppms.utils.StringUtils;
import com.jfinal.core.Controller;

/**
 * Controller基础封装-实现对jsonp格式的支持
 * @author jiangli(modify)
 * @date 2013-04-15
 */
public class BaseController extends Controller {
	
	/**
	 * 将页面传递的参数封装到Map中
	 * @return
	 */
	public Map<String,String> getParams(){
		Map<String,String> map = new HashMap<String, String>();
		Map<String,String[]> params = getParaMap();
		for(String key: params.keySet()) {
			StringBuffer sb = new StringBuffer();
			String[] ary = params.get(key);
			for(int i = 0; i < ary.length; i++){
			  sb.append(ary[i]+",");
			}
			String newStr = sb.toString();
			if(!"".equals(newStr)){
				newStr = newStr.substring(0, newStr.length()-1);
			}
			map.put(key, newStr);
		}
		return map;
	}
	
	public void renderAjax() {
		this.renderAjax(true);
	}
	
	public void renderAjax(boolean success){
		if(success){
			this.renderAjax(success,"成功");
		}else{
			this.renderAjax(success,"失败");
		}
	}
	
	/**
	 * 返回jsonp要求的数据格式
	 * @param success
	 * @param message
	 */
	public void renderAjax(boolean success, String message) {
		Success obj = new Success();
		obj.setSuccess(success);
		obj.setMessage(message);
        String callback = null;
		if (getPara("callback") != null) {
			callback = getPara("callback");
		}
		String Json = StringUtils.renderAjax(callback, obj);
		renderText(Json);
	}

	/**
	 * 返回页面grid数据
	 * @param totalCount
	 * @param root
	 */
	public void renderGrid(int totalCount, Object root) {
		String callback = null;
		if(getPara("callback") != null) {
			callback = getPara("callback");
		}
		String Json = StringUtils.renderGrid(callback, root);
		renderText(Json);
	}
	
	/**
	 * 返回页面grid数据
	 * @param totalCount
	 * @param root
	 */
	public void renderGrid(Object root) {
		String callback = null;
		if(getPara("callback") != null) {
			callback = getPara("callback");
		}
		String Json = StringUtils.renderGrid(callback, root);
		renderText(Json);
	}
}
